#coding=utf-8
import math

def average(alist):
    return sum(alist)/float(len(alist))

def median(alist):
    another = alist[:]
    another.sort()
    
    n = len(another)
    if n%2 == 0:
        return (another[n/2-1] + another[n/2])/2.0
    else:
        return another[n/2]

def last_index(alist, v):
    '''列表中最后一个v的index'''
    another = alist[:]
    
    another.reverse()
    n = another.index(v)
    
    return len(another)-1-n 
    
def histogram(data, bins, percented=False):
    '''直方图: >前一个, <=后一个
       if perceted:返回百分比;
    '''
    w = data + bins
    w.sort()
    #print w
    
    indexs = []
    for bin in bins:
        indexs.append( last_index(w, bin))
    
    r = []
    for i in range(len(bins)-1):
        r.append( indexs[i+1] - indexs[i] - 1 )
    
    r.insert(0, indexs[0]-0)
    r.append(len(w)-1-indexs[-1])
    
    length = len(data)
    if percented:r = [i*100/length for i in r] 
    return r
                
    
    
